/*
 * @Description:缓存读写
 * @Author: maskMan
 * @LastEditTime: 2025-02-18 13:38:03
 */
const storage = require("node-persist");
export default class StorBase {
  private static _dir = "../res/file/mydata";
  /**初始化 */
  public static init() {
    try {
      storage.initSync({
        dir: this._dir, // 数据存储路径
        encoding: "utf8", // 编码格式
        logging: true, // 启用日志输出
        forgiveParseErrors: false // 错误解析时是否忽略
      });
    } catch (error) {
      console.log(error);
    }
  }
  //设置缓存数据
  public static setData(key: string, data: any): Promise<boolean> {
    return new Promise((resolve) => {
      try {
        storage.setItem(key, data).then(() => {
          return resolve(true);
        });
      } catch (error) {
        console.log(error);
        return resolve(false);
      }
    });
  }
  //获取缓存数据
  public static getData(key: string): Promise<any> {
    return new Promise((resolve) => {
      try {
        storage.getItem(key).then((value) => {
          return resolve(value);
        });
      } catch (error) {
        console.log(error);
        return resolve(null);
      }
    });
  }
  //清理缓存数据
  public static async clearData() {
    await storage.clear();
  }
  //移除指定数据
  public static removeData(key: string) {
    storage.removeItem(key);
  }
  //移除指定多个数据
  public static removeDataList(keyList: string[]) {
    storage.removeItems(keyList);
  }
  //自增数据
  /**
   * @description: 获取自增缓存数字
   * @param {number} defValue 初始值
   * @param {number} incNum 自增量
   * @return {*}
   */
  public static async getIncData(key: string, defValue: number = 1000, incNum: number = 1): Promise<number> {
    try {
      const result = await this.getData(key);
      if (result != undefined && result != null) {
        const value = Number(result) + incNum;
        await this.setData(key, value);
        return Promise.resolve(Number(result) + incNum);
      }
      const value = defValue + incNum;
      await this.setData(key, value);
      return Promise.resolve(defValue + incNum);
    } catch (error) {
      console.log(error);
      return Promise.resolve(defValue + incNum);
    }
  }
}
